package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JdbcUtils {
    // 单例实例
    private static JdbcUtils instance;
    private Connection connection;

    // 私有构造函数防止实例化
    private JdbcUtils() {
        try {
            // 加载JDBC驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 获取数据库连接
            String url;
            String user;
            String password;
            if (OSUtils.isWindows()) {
                url = "jdbc:mysql://110.41.6.107:33306/ry-cloud";
                user = "root";
                password = "root";
            } else {
                url = "jdbc:mysql://192.168.0.26:3306/ry-cloud";
                user = "root";
                password = "gni2PbgxMNutdxz";
            }
            this.connection = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    // 获取单例实例
    public static JdbcUtils getInstance() {
        if (instance == null) {
            synchronized (JdbcUtils.class) {
                if (instance == null) {
                    instance = new JdbcUtils();
                }
            }
        }
        return instance;
    }

    // 获取数据库连接
    public Connection getConnection() {
        return connection;
    }

    // 关闭数据库连接
    public void closeConnection() {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
